package com.dc.service.impl;

import com.dc.dao.RoleDao;
import com.dc.model.RolePermission;
import com.dc.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleDao roleDao;

    public Map<String, String> getRolePermissionByUserId(int user_id) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        List<RolePermission> list = roleDao.selectRolePermissionByUserId(user_id);
        for (RolePermission item : list) {
            String values = map.get(item.getAuth_level());
            if (values == null) {
                map.put(String.valueOf(item.getAuth_level()), item.getPermission_value());
            } else {
                StringBuilder value1 = new StringBuilder(values);
                //从map中取得已有的权限
                StringBuilder value2 = new StringBuilder(item.getPermission_value());
                //从查询数据库取得权限
                for (int i = 0; i < value1.length(); i++) {
                    if (i >= value2.length()) {
                        //如果value1的长度大于value2，则之后的权限不做处理
                        continue;
                    } else if (value1.charAt(i) != '1' && value2.charAt(i) == '1') {
                        value1.replace(i, i + 1, "1");
                    }
                }
                if (value2.length() > value1.length()) {
                    //如果value2的长度大于value的长度，则截取value2长于value1的长度做合并
                    value1.append(value2.substring(value1.length()));
                }
                map.put(String.valueOf(item.getAuth_level()), value1.toString());
            }
        }
        return map;
    }

}
